﻿using System;
using System.Configuration;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
using System.IO;

namespace SqlLdrHelper
{
    class Program
    {
        private static List<string> _ctlFiles;
        private static List<string> CtlFiles
        {
            get
            {
                if (_ctlFiles == null)
                {
                    _ctlFiles = ConfigurationManager.AppSettings["CtlFiles"].ToString().Split(',').ToList();
                }
                return _ctlFiles;
            }
        }

        static void Main(string[] args)
        {
            try
            {
                Console.WriteLine(string.Format("{0} .ctl files found in config", CtlFiles.Count.ToString()));
                Console.WriteLine("Press 1 to proceed these files or any other key to exit:");
                
                var k = Console.ReadKey();
                if (k.KeyChar != '1')
                    return;

                Console.WriteLine("");
                string oracleUser = ConfigurationManager.AppSettings["OracleUser"].ToString();

                foreach (string item in CtlFiles)
                {
                    Console.WriteLine("");
                    Console.WriteLine(string.Format("File {0} proceed...", item));
                    if (!File.Exists(item))
                    {
                        Console.WriteLine("File not exists!");
                        continue;
                    }

                    string cmd = "sqlldr";
                    string arg = string.Format("{0} {1}", oracleUser, item);

                    ProcessStartInfo procStInfo = new ProcessStartInfo(cmd, arg);
                    procStInfo.RedirectStandardOutput = false;
                    procStInfo.UseShellExecute = true;
                    procStInfo.Verb = "runas";
                    
                    Process proc = new System.Diagnostics.Process();
                    proc.StartInfo = procStInfo;
                    try
                    {
                        proc.Start();
                        proc.WaitForExit();
                        Console.WriteLine("Completed successfully!");
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e.Message);
                    }
                }

                Console.WriteLine("");
                Console.WriteLine("Press any key to exit...");
                Console.ReadKey();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine("Press any key to exit...");
                Console.ReadKey();
            }
        }
    }
}
